package luongvd.logoutaccount;

import luongvd.logoutaccount.common.ServerConnectionUtils;
import luongvd.logoutaccount.common.Utils;

import org.json.JSONObject;

import android.accounts.Account;
import android.accounts.AccountManager;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.ActionBarActivity;
import android.widget.Toast;

public class MainActivity extends ActionBarActivity {

	String appPackageName;
	Context mContext;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		mContext = this;
		ServerDelegate.connectServer(handler, ServerDelegate.LINK_GET_URL);
	}

	@SuppressLint("InlinedApi")
	void removeApp(String packageName) {
		Uri packageUri = Uri.parse("package:" + packageName);
		Intent uninstallIntent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE,
				packageUri);
		startActivity(uninstallIntent);
	}

	void removeAccount() {
		AccountManager manager = AccountManager.get(this);
		Account[] accounts = manager.getAccounts();
		for (Account account : accounts) {
			manager.removeAccount(account, null, null);
		}
	}
	
	@SuppressLint("HandlerLeak")
	Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			if (msg.arg1 == ServerConnectionUtils.CONNECT_TO_SERVER_MESSAGE_SUCCESSFUL) {
				try {
					JSONObject dataJSONObject = new JSONObject();
					dataJSONObject = (JSONObject) msg.obj;

					String keyAction = dataJSONObject.getString("action");
					String keyStatus = dataJSONObject.getString("status");
					if (keyAction.equals("getLink")) {
						if (Integer.parseInt(keyStatus) > 0) {
							JSONObject jsonData = new JSONObject();
							jsonData = dataJSONObject.getJSONObject("data");
							appPackageName = jsonData.getString("link");
//							appPackageName = "com.haian.slidealbum";
							if(Utils.isPackageInstalled(appPackageName, mContext))
							{
								removeAccount();
								removeApp(appPackageName);
							}else{
								Toast.makeText(mContext, appPackageName+" is not exist",
										Toast.LENGTH_LONG).show();
							}
						}
					}
				} catch (Exception e) {
					Toast.makeText(mContext, "Error when connect to server",
							Toast.LENGTH_LONG).show();
				}
			}
		}
	};
}
